/*******************************************************************************
 * 导入excel（客户在途上报（按月））
 ******************************************************************************/


function checkImpZTForMonth(cid, importDate, ztId, callback) {
    $.ajax({
        type: 'post',
        url: _m_url + 'fxa/getFxZTByDate',
        data: {'clientId': cid, 'Date': importDate, 'ztId': ztId},
        success: function (data) {
            if (data.rows.length > 0) {
                $(importDate).val('');
                $.messager.alert("提示信息", "亲，当前客户当月已上报过，请重新选择！");
            } else {
                callback();
            }
        }
    });
}

function loadDataExcFxZTbyMonth(dsId, flag) {
    var cid = "";  //客户编号
    var importDate = "";    //获取导入日期
    var ztId = "";
    if (dsId == "ds_fx_MonthZT1" && flag == "fmzt") {   //客户实销上报(按月)
        cid = $('#' + flag + '_addWinTable input[qucln=CLIENT_ID]').val();
        importDate = $('#' + flag + '_addWinTable input[qucln=IMPORT_DATE]').val();
        ztId = $('#' + flag + '_addWinTable input[qucln=ZT_ID]').val();
        if (cid == null || cid == "") {
            $.messager.alert("提示信息", "请选择客户!");
            return;
        }
        if (importDate == null || importDate == "") {
            $.messager.alert("提示信息", "请选择导入日期!");
            return;
        }

        checkImpZTForMonth(cid, importDate, ztId, function () {
            if ($('#IMP_EXC_WIN').length > 0) {
                $('#IMP_EXC_PARENT_PANEL').window('open');
                var obj = document.getElementById("IMP_EXC_WIN");
                document.body.removeChild(obj);
            }
            var div_box = document.createElement("DIV");
            div_box.id = "IMP_EXC_WIN";
            div_box.height = 100;
            document.body.appendChild(div_box);
            var dsid = $('#' + flag + '_SAVE_BUT').attr('dsid');
            var keys = $('#' + flag + '_addWinTable input[qucln]');
            var kvs = "";
            for (var i = 0; i < keys.length; i++) {
                if ($(keys[i]).attr('qucln').indexOf("ID") != -1 || $(keys[i]).attr('qucln').indexOf("MAN") != -1 || $(keys[i]).attr('qucln').indexOf("CODE") != -1) {
                    if ($(keys[i]).attr('value')) {
                        kvs += "`" + $(keys[i]).attr('qucln') + "`" + ":" + "`" + $(keys[i]).attr('value') + "`" + ",";
                    }
                }
            }
            var width = document.documentElement.clientWidth;
            var height = document.documentElement.clientHeight;
            $('#IMP_EXC_WIN').load(_m_url + 'singlePages/pageToImportZTMonth', {
                    'dsId': dsId,
                    'flag': flag,
                    'dsid': dsid
                },
                function () {
                    $("#download").attr("href", _m_url + "singlePages/dow?fileName=" + flag + ".xlsx");
                    $.parser.parse('#IMP_EXC_DG_PANEL');
                    $('#IMP_EXC_PARENT_PANEL').window({
                        width: 650,
                        height: 450,
                        draggable: true,
                        top: (height - 450) * 0.5,
                        left: (width - 650) * 0.5,
                        modal: true,
                        resizable: false,
                        closable: false,
                        collapsible: false,
                        maximizable: false,
                        minimizable: false
                    });
                });
        })
    }
}


var hisbn = null;
function initDataGrid(flg) {
    // 初始化弹窗
    $('#manage_ap').window({
        title: '手动匹配',
        width: 545,
        height: 365,
        closed: false,
        closable: false
    });
    $('#manage_app').load(
        window.parent._index_path + 'model/importExcel/MataOrderName.jsp',
        {},
        function () {
        }
    );
    $('#manage_ap').window('close');
    // 初始化datadrid;
    $('#IMP_EXC_DATALIST').datagrid({
        iconCls: 'icon-save',
        width: 620,
        height: 360,
        striped: true,
        collapsible: true,
        autoRowHeight: false,
        sortOrder: 'desc',
        remoteSort: false,
        fixed: true,
        columns: [[
            {field: 'kk', checkbox: true},
            // {field: "IS_PP", title: '是否匹配成功', formatter: convert},
            {field: "PP_DESC", title: '备注'},
            {field: "H_ISBN", title: '导入书号'},
            {field: "H_NAME", title: '匹配书名', width: 200},
            {field: "H_PRICE", title: '定价'},
            {field: "H_AMOUNT", title: '导入数量'},
            {field: "SYSPICI", title: '匹配批次', hidden: true},
            {field: "H_ID", title: '商品id', hidden: true}
        ]],
        rowStyler: function (index, row) {
            if (row.IS_PP == 0) {
                return 'background-color:#bbddf5;';
            }
        },
        singleSelect: true,
        onSelect: function (rowIndex, rowData) {
        },
        // 双击执行效果
        onDblClickRow: function (index, field, value) {
            $(this).datagrid("selectRow", index);
            var hisbn = field.H_ISBN;
            var hname = field.H_NAME;
            var str = " <div id=\"kehxscjwin\" iconCls=\"icon-save\" title=\"商品(选择一条数据单击确定加入明细)\">" +
                "<span>书号:</span>" + "<input id=\"shuhao_\" type=\"text\" >" +
                "<span>书名:</span>" + "<input id=\"shuming_\" type=\"text\" >" +
                "&nbsp;<a   class=\"easyui-linkbutton  l-btn\" iconCls=\"icon-search\" onclick=\"search2__()\">" +
                "<span class=\"l-btn-left\">" +
                "<span class=\"l-btn-text\">查询</span>" +
                "</span>" +
                "</a>" +
                "&nbsp;<a  class=\"easyui-linkbutton  l-btn\" iconCls=\"icon-save\" onclick=\"commit2__()\">" +
                "<span class=\"l-btn-left\">" +
                "<span class=\"l-btn-text\">确定</span>" +
                "</span>" +
                "</a>" +
                "<table id=\"fms_Datagrid\" style='width:450px;height:220px'>";
            str += "</table></div>";
            $("body").append(str);		// 拼接弹框的弹出层
            $("#kehxscjwin").window({
                width: 500,
                height: 300,
                modal: true,
                resizable: false,
                closable: true,
                collapsible: false,
                maximizable: false,
                minimizable: false
            });
            var shuhao = $("#shuhao_").val(hisbn);
            //查询方法
            search2__();
            $("#fms_Datagrid").datagrid({
                singleSelect: true,			// 只允许选中一条数据
                fit: true,
                columns: [[
                    {field: 'H_ISBN', title: '书号', width: 150},
                    {field: 'H_NAME', title: '书名', width: 150},
                    {field: 'H_PRICE', title: '单价', width: 50},
                    {field: 'H_DISCOUNT', title: '折扣', width: 50, hidden: true},
                    {field: 'H_AMOUNT', title: '数量', width: 50, hidden: true},
                    {field: 'H_ID', title: '主键', width: 100, hidden: true},
                    {field: 'XS_MONEY', title: '销售收入', width: 100, hidden: true},
                    {field: 'AMOUNT', title: '客户库存', width: 100, hidden: true}
                ]]
            });
        }
    });
}
// 错误信息界面==>双击人工匹配界面,查询按钮响应
function search2__() {
    var shuhao = $("#shuhao_").val();
    var shuming = $("#shuming_").val();
    $.ajax({
        url: "singlePages/queryProductBYDAY",
        data: {'H_ISBN': shuhao, "H_NAME": shuming},
        success: function (data) {
            console.log(data);
            $("#fms_Datagrid").datagrid('loadData', {"total": data.length, "rows": data});
        }
    });

}



// 返回
function importexcelBack() {
    // 文件清空
    $("#file").val('');
    $("#IMP_EXC_DATALIST").datagrid('loadData', {total: 0, rows: []});
    $('#IMP_EXC_PARENT_PANEL').window('close');
}
function importexcel(flg, dsid) {
    var cid = $('#fmzt_addWinTable input[qucln=CLIENT_ID]').val();
    var configStr = "AND CLIENT_ID= '" + $('#fmzt_addWinTable input[qucln=CLIENT_ID]').val() + "'";
    var xt_id = $('#fmzt_addWinTable input[qucln=ZT_ID]').val();
    //根据dsid重新获取kvs
    var keyes = $('#' + flg + '_addWinTable input[qucln]');
    var kvs = "";
    for (var i = 0; i < keyes.length; i++) {
        if ($(keyes[i]).attr('qucln').indexOf("ID") != -1 || $(keyes[i]).attr('qucln').indexOf("MAN") != -1 || $(keyes[i]).attr('qucln').indexOf("IMPORT_DATE") != -1) {
            if ($(keyes[i]).attr('value')) {
                kvs += "`" + $(keyes[i]).attr('qucln') + "`" + ":" + "`" + $(keyes[i]).attr('value') + "`" + ",";
            }
        }
    }

    var keys = flg + "/" + dsid + "/" + kvs
    if ($("#file").val() != "" && $("#file").val() != null) {
        if ($("#file").val().indexOf(".xls") > 0
            || $("#file").val().indexOf(".xlsx") > 0
            || $("#file").val().indexOf(".XLS") > 0
            || $("#file").val().indexOf(".XLSX") > 0
        ) {
            var mask_kk = $("<div id='mask_kk' class=\"datagrid-mask\" style='z-index:99999;'></div>")
                .css({display: "block", width: "100%", height: $(window).height()})
                .appendTo("body");
            var mask_kkk = $("<div id='mask_kkk' class=\"datagrid-mask-msg\" style='z-index:100000;'></div>")
                .html("分析Excel数据中,请稍候...")
                .appendTo("body")
                .css({
                    display: "block",
                    left: ($(document.body).outerWidth(true) - 190) / 2,
                    top: ($(window).height() - 45) / 2
                });
            $.ajaxFileUpload({
                // 处理文件上传操作的服务器端地址(可以传参数,已亲测可用)
                url: encodeURI('../..' + window.parent._index_path + 'singlePages/improtRetunInfoZT?keys=' + keys),
                type: 'post',
                secureuri: false,                    // 是否启用安全提交,默认为false
                fileElementId: 'file',               // 文件选择框的id属性
                dataType: 'json',                    // 服务器返回的格式,可以是json或xml等
                data: {"cid": cid, "configStr": configStr, "xt_id": xt_id, "flg:": flg, "dsid:": dsid, "kvs:": kvs},
                success: function (data) {        // 服务器响应成功时的处理函数
                    console.info('--------------');
                    var obj;
                    try {
                        obj = eval('(' + data.json + ')');
                    }
                    catch (e) {
                        alert('服务器已分析完毕excel,但数据有问题,请检查EXCEL!');
                        $('#mask_kkk').css("display", "none");
                        mask_kkk.remove();
                        mask_kk.remove();
                        return;
                    }
                    var dg;
                    // 回显错误信息
                    if(obj.errorData && obj.errorData.length > 0){
                        dg=$('#IMP_EXC_DATALIST');
                        dg.css('overflow-x','auto');
                        dg.datagrid('loadData',{"total":obj.errorData.length ,"rows" : obj.errorData});
                    } else {
                        if (obj.successData) {
                            // 回显正确信息 appendRow
                            importexcelBack();
                            var successData = obj.successData;
                            dg = $("#" + flg + "_addItemDatagrid");
                            dg.datagrid('loadData', {total: 0, rows: []});
                            var z_amount = 0;
                            for (var i = 0, len = successData.length; i < len; i++) {
                                dg.datagrid('appendRow', successData[i]);
                                z_amount += Number(successData[i].ZT_AMOUNT);
                            }
                            $('#fmzt_addWinTable input[qucln=Z_AMOUNT]').val(z_amount);
                            $('#fmzt_addWinTable input[qucln=Z_AMOUNT]').attr("chan", "T");
                            $('#fmzt_addWinTable input[qucln=Z_AMOUNT]').next().val(z_amount);
                        }
                    }

                    // 去除 加载效果后,如果有消息的话 就提示
                    if (obj.errmsg) {
                        alert(obj.errmsg);
                    }
                    // 去掉蒙板
                    mask_kkk.remove();
                    mask_kk.remove();
                }// 结束响应成功
            });
        } else {
            $.messager.alert('警告', '文件必须为Excel文件');
        }
    } else {
        $.messager.alert('警告', '上传文件不允许为空');
    }

}

